<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author YDZ
-->
<template>
  <div>
    <BasicTable @register="registerTable">
      <template #tableTitle>
        <Icon :icon="getTitle.icon" class="m-1 pr-1" />
        <span> {{ getTitle.value }} </span>
      </template>
      <template #toolbar>
        <!-- <a-button type="primary" @click="handleForm({})" v-auth="'srm:asn:vouch:asnH:edit'">
          <Icon icon="i-fluent:add-12-filled" /> {{ t('新增') }}
        </a-button> -->
        <a-button type="default" @click="handlePrint({})" v-auth="'srm:asn:vouch:asnH:view'">
          <Icon icon="simple-line-icons:printer" /> {{ t('打印') }}
        </a-button>
      </template>
      <template #firstColumn="{ record }">
        <a @click="handleForm({ djno: record.djno })">
          {{ record.djno }}
        </a>
      </template>
    </BasicTable>
    <InputForm @register="registerDrawer" @success="handleSuccess" />
    <BpmRuntimeTrace @register="registerTraceModal" />
    <PrintDrawer @register="registerPrintDrawer" />
    <component
      :is="inputFormComponent"
      v-model:open="inputFormVisible"
      @register="registerDrawerBpmMyTask"
      @success="handleSuccess"
    />
  </div>
</template>
<script lang="ts" setup name="ViewsSrmAsnVouchAsnHList">
  import { unref,onMounted, shallowRef, ref, ComponentOptions } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicTable, BasicColumn, useTable } from '/@/components/Table';
  import { asnHDelete, asnHListData, asnHDisabel } from '/@/api/srm/asn/vouch/asnH';
  import { useDrawer } from '/@/components/Drawer';
  import { useModal } from '/@/components/Modal';
  import { BpmRuntimeTrace } from '/@/components/Bpm';
  import { FormProps } from '/@/components/Form';
  import InputForm from './form.vue';
  import PrintDrawer from '/@/components/print/printDrawer.vue';
  import { companyTreeData } from '/@/api/sys/company';
  import { useUserStore } from '/@/store/modules/user';
  import { bpmTaskDefForm } from '/@/api/bpm/myTask';
  import { dynamicImport } from '/@/router/helper/routeHelper';
  import { createAsyncComponent } from '/@/utils/factory/createAsyncComponent';
  import qs from 'qs';
  const userStore = useUserStore();

  const { t } = useI18n('srm.asn.vouch.asnH');
  const { showMessage } = useMessage();
  const { meta } = unref(router.currentRoute);

  const getTitle = {
    icon: meta.icon || 'i-ant-design:book-outlined',
    value: meta.title || t('送货单管理'),
  };

  const searchForm: FormProps = {
    baseColProps: { lg: 6, md: 8 },
    labelWidth: 90,
    schemas: [
      {
        label: t('公司'), 
        field: 'pkCorp',
        fieldLabel: 'company.companyName',
        component: 'TreeSelect',
        componentProps: {
          api: companyTreeData,
          // params: {
          //   isShowCode: true,
          // },
          allowClear: true,
          immediate: true,
        },
      },
      {
        label: t('ASN单号'),
        field: 'djno',
        component: 'Input',
      },
      {
        label: t('创建日期'),
        field: 'createDate',
        component: 'RangePicker',
      },
      {
        label: t('供应商'),
        field: 'basVen.cusname',
        component: 'Input',
      },
      {
        label: t('采购员'),
        field: 'cgName',
        component: 'Input',
      },
      {
        label: t('采购部门'),
        field: 'cgDeptName',
        component: 'Input',
      },
      {
        label: t('创建人'),
        field: 'createByName',
        component: 'Input',
      },
      {
        label: t('单据状态'),
        field: 'djStatus',
        component: 'Select',
        componentProps: {
          dictType: 'xy_asn_dj_status',
          allowClear: true,
        },
      },
      {
        label: t('审批状态'),
        field: 'status',
        component: 'Select',
        componentProps: {
          dictType: 'bpm_biz_status',
          allowClear: true,
          onChange: handleSuccess,
        },
      },
      {
        label: t('预计到货'),
        field: 'planArrDate',
        component: 'RangePicker',
        componentProps: {
        },
      },
      {
        label: t('收货人'),
        field: 'arrUserName',
        component: 'Input',
      },
      {
        label: t('收货时间'),
        field: 'arrDate',
        component: 'RangePicker',
        componentProps: {
          // format: 'YYYY-MM-DD HH:mm',
          // showTime: { format: 'HH:mm' },
        },
      },
    ],
    fieldMapToTime: [['planArrDate', ['planArrDate_gte', 'planArrDate_lte']],['createDate', ['createDate_gte', 'createDate_lte']],['arrDate', ['arrDate_gte', 'arrDate_lte']]],
  };

  const tableColumns: BasicColumn[] = [
    {
      title: t('ASN单号'),
      dataIndex: 'djno',
      key: 'a.djno',
      sorter: true,
      width: 180,
      align: 'left',
      slot: 'firstColumn',
    },
    {
      title: t('公司'),
      dataIndex: 'company.companyName',
      key: 'a.pk_corp',
      sorter: true,
      width: 180,
      align: 'left',
    },
    {
      title: t('供应商'),
      dataIndex: 'basVen.cusname',
      key: 'a.ven_id',
      sorter: true,
      width: 130,
      align: 'left',
    },
    {
      title: t('仓库'),
      dataIndex: 'wareName',
      key: 'a.ware_name',
      sorter: true,
      width: 130,
      align: 'left',
    },
    {
      title: t('采购员'),
      dataIndex: 'cgName',
      key: 'a.cg_name',
      sorter: true,
      width: 100,
      align: 'center',
    },
    {
      title: t('采购部门'),
      dataIndex: 'cgDeptName',
      key: 'a.cg_dept_name',
      sorter: true,
      width: 100,
      align: 'center',
    },
    {
      title: t('业务流程'),
      dataIndex: 'busTypeName',
      key: 'a.bus_type_name',
      sorter: true,
      width: 130,
      align: 'left',
    },
    {
      title: t('送货总数'),
      dataIndex: 'sumQty',
      key: 'a.sum_qty',
      sorter: true,
      width: 100,
      align: 'center',
    },
    {
      title: t('预计到货'),
      dataIndex: 'planArrDate',
      key: 'a.plan_arr_date',
      sorter: true,
      width: 120,
      align: 'center',
    },
    {
      title: t('创建人'),
      dataIndex: 'createByName',
      key: 'a.create_by_name',
      sorter: true,
      width: 100,
      align: 'left',
    },
    {
      title: t('创建时间'),
      dataIndex: 'createDate',
      key: 'a.create_date',
      sorter: true,
      width: 130,
      align: 'center',
    },
    {
      title: t('收货人'),
      dataIndex: 'arrUserName',
      key: 'a.arr_user_name',
      sorter: true,
      width: 100,
      align: 'left',
    },
    {
      title: t('收货时间'),
      dataIndex: 'arrDate',
      key: 'a.arr_date',
      sorter: true,
      width: 100,
      align: 'center',
    },
    {
      title: t('收货反馈'),
      dataIndex: 'arrRemarks',
      key: 'a.arr_remarks',
      sorter: true,
      width: 130,
      align: 'left',
    },
    {
      title: t('收货总数'),
      dataIndex: 'sumArrQty',
      key: 'a.sum_arr_qty',
      sorter: true,
      width: 100,
      align: 'right',
    },
    {
      title: t('单据状态'),
      dataIndex: 'djStatus',
      key: 'a.dj_status',
      sorter: true,
      width: 100,
      align: 'center',
      dictType:'xy_asn_dj_status',
      fixed:'right'
    },
    {
      title: t('审批状态'),
      dataIndex: 'status',
      key: 'a.status',
      sorter: true,
      width: 100,
      align: 'center',
      dictType: 'bpm_biz_status',
      fixed:'right'

    },
   
    {
      title: t('备注信息'),
      dataIndex: 'remarks',
      key: 'a.remarks',
      sorter: true,
      width: 130,
      align: 'left',
    },
  ];

  const actionColumn: BasicColumn = {
    align: 'left',
    width: 160,
    actions: (record: Recordable) => [
      {
        icon: 'i-clarity:note-edit-line',
        title: t('编辑送货单'),
        onClick: handleForm.bind(this, { djno: record.djno }),
        auth: 'srm:asn:vouch:asnH:edit',
      },
      {
        icon: 'i-ant-design:delete-outlined',
        color: 'error',
        title: t('删除送货单'),
        popConfirm: {
          title: t('是否确认删除送货单'),
          confirm: handleDelete.bind(this, record),
        },
        auth: 'srm:asn:vouch:asnH:delete',
        ifShow: () => record.status == '9',
      },
      {
        icon: 'i-fluent:flowchart-20-regular',
        title: t('流程追踪'),
        onClick: handleTrace.bind(this, record),
        ifShow: () => record.status != '9',
      },
      {
        icon: 'mdi:checkbox-marked-outline',
        title: t('任务办理'),
        onClick: handleBpmMyTask.bind(this, { id: record.id }),
        ifShow: () => record.status == '4' || record.status == '5' || record.status == '6',
      },
      {
        icon: 'i-ant-design:close-circle-outlined',
        color: 'error',
        title: t('作废送货单'),
        popConfirm: {
          title: t('是否确认作废送货单'),
          confirm: handleCancel.bind(this, record),
        },
        auth: 'srm:asn:vouch:asnH:disabel',
        ifShow: () => record.djStatus == '1',
      },
    ],
  };

  const [registerDrawer, { openDrawer }] = useDrawer();
  const [registerTable, { reload,getSelectRows,getForm }] = useTable({
    api: asnHListData,
    beforeFetch: (params) => {
      return params;
    },
    columns: tableColumns,
    actionColumn: actionColumn,
    formConfig: searchForm,
    showTableSetting: true,
    useSearchForm: true,
    canResize: true,
    rowSelection: {
      type: 'checkbox',
    },
    immediate: false,
  });

  function handleForm(record: Recordable) {
    openDrawer(true, record);
  }

  async function handleDelete(record: Recordable) {
    const params = { djno: record.djno };
    const res = await asnHDelete(params);
    showMessage(res.message);
    handleSuccess(record);
  }

  async function handleCancel(record: Recordable) {
    const params = { djno: record.djno };
    const res = await asnHDisabel(params);
    showMessage(res.message);
    handleSuccess(record);
  }

  function handleSuccess(record: Recordable) {
    reload({ record });
  }

  const [registerPrintDrawer, { openDrawer: openPrintDrawer }] = useDrawer();
  const [registerTraceModal, { openModal: traceModel }] = useModal();

  function handleTrace(record: Recordable) {
    traceModel(true, { formKey: 'Flow_Srm_Asn_h', bizKey: record.id });
  }

  const [registerDrawerBpmMyTask, { setDrawerData }] = useDrawer();
  const inputFormComponent = shallowRef<Nullable<any>>(null);
  const inputFormVisible = ref<Boolean>(false);
  async function handleBpmMyTask(record: Recordable) {
    const data = await bpmTaskDefForm({ formKey: 'Flow_Srm_Asn_h', bizKey: record.id });
    if (data.result == 'true') {
      const url = data.pcUrl;
      const idx = url.indexOf('?');
      // component
      let component: ReturnType<typeof defineComponent>;
      const compStr = idx == -1 ? url : url.substring(0, idx);
      if (compStr && compStr != '') {
        const imp = dynamicImport(compStr);
        if (imp) component = createAsyncComponent(imp);
      }
      // params
      let params = {};
      const paramStr = idx == -1 ? '' : url.substring(idx + 1);
      if (paramStr && paramStr != '') {
        params = qs.parse(paramStr);
      }
      // open
      if (component) {
        inputFormComponent.value = component;
        inputFormVisible.value = true;
        setDrawerData(params);
      }
    } else {
      showMessage(data.message);
    }
  }

  // 打印
  async function handlePrint() {
    let arr = await getSelectRows();
    if (getSelectRows().length == 0) {
      showMessage(t('请先选择数据'));
      return;
    }
    const idsArr = arr.map((item) => {
      return item.id;
    });
    let params = {
      ids: idsArr.join(','),
      title: '送货单打印',
      height: '0.96',
      width: '0.8',
      fileName: 'printAsn',
    };
    openPrintDrawer(true, params);
  }

  // 默认查询条件
  onMounted(async () => {
    handleCompany();
  });

  async function handleCompany() {
    await getForm().setFieldsValue({
      pkCorp: userStore.getProjecte.code,
    });
    reload();
    await getForm().setFieldsValue({
      pkCorp: userStore.getProjecte.code,
    });
  }
</script>
